;(async function() {
  const cheerio = require('cheerio');
  const puppeteer = require('puppeteer');
  const fs = require('fs');
  const browser = await puppeteer.launch({
    headless: false, // 有浏览器界面启动
    slowMo: 100, // 放慢浏览器执行速度，方便测试观察
    args: [ // 启动 Chrome 的参数，详见上文中的介绍
      '–no-sandbox',
      '--window-size=1280,960'
    ]
  });
  const page = await browser.newPage();
  await page.goto(
    'https://list.tmall.com/search_product.htm?spm=a221t.1476805.cat.19.52006769d615Pr&cat=54290107&q=%E4%BC%91%E9%97%B2%E5%A5%97%E8%A3%85'
  );
  const html = await page.content();
  const $ = cheerio.load(html, {
    normalizeWhitespace: true,
    decodeEntities: false
  });
  const goods = [];
  const price = [];
  const saleNum = [];
  $('.productTitle a').each((i, elem) => {
    goods.push($(elem).attr('title'));
  });
  $('.productPrice em').each((i, elem) => {
    price.push($(elem).attr('title'));
  });
  $('.productStatus em').each((i, elem) => {
    saleNum.push($(elem).text());
  });
  const result = goods.reduce((current, item, i) => {
    return `${current}\n${item},¥${price[i]},${saleNum[i]}`;
  }, '');
  fs.appendFile(
    './spider/tmall.csv',
    '商品,价格,月成交' + result,
    'utf8',
    err => {
      if (err) throw err;
      console.log('数据已被追加到文件');
    }
  );
  await page.close();
  await browser.close();
})();
